export class DateTim {
    private startTime: number;
    private duration: number;
    private callback: (elapsedTime: number) => void;
    private _isStop:boolean;
    private timeoutId:number

    constructor(callback: (elapsedTime: number) => void, durationInSeconds: number) {
        this.duration = durationInSeconds * 1000; // 转换为毫秒
        this.callback = callback;
        this.timeoutId = null;
    }

    start() {
        this.stop();
        this._isStop = false;
        this.startTime = Date.now();
        const runTimer = () => {
            if(!this._isStop)
            {
                const currentTime = Date.now();
                const elapsedTimeInSeconds = Math.floor((currentTime - this.startTime) / 1000);
                this.callback(elapsedTimeInSeconds);
                this.timeoutId = setTimeout(runTimer, 1000); // 每秒触发一次
            }
            
        };
        runTimer();
    }
    stop() {
        if (this.timeoutId) {
            this._isStop = true;
            clearTimeout(this.timeoutId);
            this.timeoutId = null;
        }
    }
}


